package com.scau.clothes.service.impl;

import com.scau.clothes.dao.UserMoneyDao;
import com.scau.clothes.pojo.Order;
import com.scau.clothes.pojo.enumclass.OrderStatus;
import com.scau.clothes.pojo.enumclass.PayType;
import com.scau.clothes.service.PayService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;

@Service
public class PayServiceImpl implements PayService {
    private static String PAY_TYPE="PAY_TYPE";

    @Autowired
    UserMoneyDao userMoneyDao;
    @Override
    @Transactional
    public Order pay(int userId, Order order, BigDecimal actualPay,int payType) {
        Order res = new Order();
        if(payType==1)
            res = payByCash(userId,actualPay,order);
        else if(payType==2)
            res = payOnline(userId,order);
        else if(payType==3)
            res = payByBankCart(userId,order);
        order.setOrderStatus(OrderStatus.PAYED);
        return res;
    }
    private Order payByCash(int userId, BigDecimal actualPay,Order order){
        order.setActualPayment(actualPay);
        BigDecimal res = order.getActualPayment().subtract(order.getActualPrice());
        if (res.compareTo(BigDecimal.ZERO)==-1) {
            throw new RuntimeException("现金不足");
        }
        order.setCharge(res);
        order.setPayType(PayType.CASH);
        return order;
    }
    private Order payOnline(int userId,Order order){
        order.setActualPayment(order.getActualPrice());
        if (userMoneyDao.updateCostByUserId(userId,order.getActualPayment())!=1) {
            throw new RuntimeException("余额不足");
        }
        order.setPayType(PayType.ONLINE);
        return order;
    }
    private Order payByBankCart(int userId,Order order){
        order.setPayType(PayType.BANK_CARD);
        order.setActualPayment(order.getActualPrice());
        return order;
    }

}
